/* eslint-disable no-unused-vars */
/* eslint-disable react/prop-types */
import React from 'react';
import { Form, Input, Row, Col, Button, Tree, Select, TreeSelect, Switch,message } from 'antd';
import { withRouter } from 'react-router-dom';
import Api from '@/api/index'

const { TreeNode } = Tree;
const { Option } = Select;

class UserForm extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            confirmDirty: false,
            treeData: [],
            selectData: []
        }
    }

    componentDidMount() {
        //获取列表
        this.getStructList()
        this.getRoleList()
    }

    handleSubmit = e => {
        e.preventDefault();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err) {
                const { status, ...other } = values;
                Api.createUser({ ...other, status: status ? 1 : 0 }).then(res => {
                    if (res.code == 200) {
                        message.success('保存成功')
                    }
                })
            }
        });
    };

    handleConfirmBlur = e => {
        const { value } = e.target;
        this.setState({ confirmDirty: this.state.confirmDirty || !!value });
    };

    compareToFirstPassword = (rule, value, callback) => {
        const { form } = this.props;
        if (value && value !== form.getFieldValue('password')) {
            callback('两次输入的密码不一致');
        } else {
            callback();
        }
    };

    validateToNextPassword = (rule, value, callback) => {
        const { form } = this.props;
        if (value && this.state.confirmDirty) {
            form.validateFields(['confirm'], { force: true });
        }
        callback();
    };


    handleRoleChange = (value) => {
        this.props.form.setFieldsValue({
            roleList: value
        })
    }

    onPidChange = (value) => {
        const { setFieldsValue } = this.props.form;
        setFieldsValue({ structId: value[0] })
    }

    //组织机构列表
    getStructList = () => {
        Api.getStructList().then(res => {
            if (res.code == 200) {
                this.setState({ treeData: res.data.result })
            }
        })
    };
    renderTree = (treeData) => {
        return treeData.map((item) => {
            if (item.children && Array.isArray(item.children)) {
                return (
                    <TreeNode title={item.name} key={item.id} value={item.id}>
                        {this.renderTree(item.children)}
                    </TreeNode>
                );
            }
            return <TreeNode title={item.name} key={item.id} value={item.id} />;
        });
    };
    //角色列表
    getRoleList = () => {
        Api.getRoleList({isPage:false}).then(res => {
            if (res.code == 200) {
                this.setState({ selectData: res.data.result })
            }
        })
    };
    renderSelect = (selectData) => {
        return selectData.map((item) => {
            return <Option value={item.id} label={item.title} key={item.id}>
                {item.title}
                <span style={{ marginLeft: '6px' }} role="img" aria-label={item.title}>（{item.description}）</span>
            </Option>
        });
    };

    render() {
        const { getFieldDecorator } = this.props.form;
        const { treeData, selectData } = this.state;
        const formItemLayout = {
            labelCol: {
                xs: { span: 24 },
                sm: { span: 4 },
            },
            wrapperCol: {
                xs: { span: 24 },
                sm: { span: 20 },
            },
        };
        const tailFormItemLayout = {
            wrapperCol: {
                xs: {
                    span: 24,
                    offset: 0,
                },
                sm: {
                    span: 22,
                    offset: 2,
                },
            },
        };

        return (
            <Form {...formItemLayout} onSubmit={this.handleSubmit}>
                <Form.Item label="所属机构">
                    {getFieldDecorator('structId', {
                        rules: [
                            { required: true, message: '请选择所属机构' },
                        ],
                    })(<TreeSelect
                        style={{ width: '100%' }}
                        dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                        placeholder="请选择所属机构"
                        allowClear
                        treeDefaultExpandAll
                        onChange={this.onPidChange}
                    >
                        {this.renderTree(treeData)}
                    </TreeSelect>)}
                </Form.Item>
                <Form.Item label="用户名">
                    {getFieldDecorator('username', {
                        rules: [
                            {
                                required: true,
                                message: '请输入用户名',
                            },
                        ],
                    })(<Input />)}
                </Form.Item>
                <Form.Item label="密码" hasFeedback>
                    {getFieldDecorator('password', {
                        rules: [
                            {
                                required: true,
                                message: '请输入登录密码',
                            },
                            {
                                validator: this.validateToNextPassword,
                            },
                        ],
                    })(<Input.Password />)}
                </Form.Item>
                <Form.Item label="确认密码" hasFeedback>
                    {getFieldDecorator('confirm', {
                        rules: [
                            {
                                required: true,
                                message: '确认密码',
                            },
                            {
                                validator: this.compareToFirstPassword,
                            },
                        ],
                    })(<Input.Password onBlur={this.handleConfirmBlur} />)}
                </Form.Item>
                <Form.Item label="用户角色">
                    {getFieldDecorator('roleList', {
                        rules: [{ required: true, message: '请分配用户角色' }]
                    })(<Select
                        mode="multiple"
                        style={{ width: '100%' }}
                        placeholder="分配用户角色"
                        onChange={this.handleRoleChange}
                        optionLabelProp="label"
                    >
                        {this.renderSelect(selectData)}
                    </Select>)}
                </Form.Item>
                <Form.Item label="邮箱">
                    {getFieldDecorator('email', {
                        rules: [
                            {
                                type: 'email',
                                message: '邮箱格式不正确',
                            },
                            {
                                required: true,
                                message: '请输入邮箱',
                            },
                        ],
                    })(<Input />)}
                </Form.Item>

                <Form.Item label="用户手机号">
                    {getFieldDecorator('mobile', {
                        rules: [{ required: true, message: '请输入用户手机号' }],
                    })(<Input style={{ width: '100%' }} />)}
                </Form.Item>
                <Form.Item label="手机验证码" extra="6位数的验证码">
                    <Row gutter={8}>
                        <Col span={12}>
                            {getFieldDecorator('authcode', {
                                rules: [{ required: true, message: '请输入手机验证码' }],
                            })(<Input />)}
                        </Col>
                        <Col span={12}>
                            <Button>获取验证码</Button>
                        </Col>
                    </Row>
                </Form.Item>
                <Form.Item label="用户状态">
                    {getFieldDecorator('status', { valuePropName: 'checked' })(<Switch />)}
                </Form.Item>

                <Form.Item {...tailFormItemLayout} style={{ marginTop: '30px', textAlign: 'center' }}>
                    <Button className="submit_btn" type="default">取消</Button>
                    <Button className="submit_btn" type="primary" htmlType="submit">确定</Button>
                </Form.Item>
            </Form>
        );
    }
}

export default Form.create()(withRouter(UserForm));
